package com.xpoint.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.xpoint.backend.common.BaseContext;
import com.xpoint.backend.common.R;
import com.xpoint.backend.entity.User;
import com.xpoint.backend.mapper.UserMapper;
import com.xpoint.backend.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

@Service
//用户业务逻辑层
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public R<User>    userLogin(User user, HttpServletRequest request) {
//        先判断对象是否为空
        if (user.getUserName()!=null) {
//            创建条件构造器
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            查询条件，username=getUserName  or getEmail==getUserName
            lambdaQueryWrapper.eq(User::getUserName,user.getUserName()).or().eq(User::getEmail,user.getUserName());
//            查询一个对象
            User one = this.getOne(lambdaQueryWrapper);
            if (one!=null) {
//              获取查询数据库的密码
                String onePassword = one.getPassword();
//                获取传过来的密码，并且md5加密
                String userPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
//                判断密码是否相等
                if (userPassword.equals(onePassword)){
//                    设置id到session中
                    request.getSession().setAttribute("userId", one.getId());
                    return R.success(one);
                }else{
                    return R.error("密码错误");
                }
            }else {
                return R.error("用户名错误");
            }
        }
        return R.error("登录失败，未知错误");
    }

    @Override
    @Transactional
    public R<String> userRegister(User user) {
        if (user!=null){
            String userPassword = user.getPassword();
//            将获取到的密码MD5加密
            String md5DigestAsHex = DigestUtils.md5DigestAsHex(userPassword.getBytes());
//            再重新赋值给user对象
            user.setPassword(md5DigestAsHex);
//            数据库添加
            boolean save = this.save(user);
            if (save){
                return R.success("注册成功");
            }else {
                return R.error("注册失败");
            }
        }

        return R.error("注册失败");
    }

    @Override
    public R<User> findUser() {
        Long currentId = BaseContext.getCurrentId();
        User byId = getById(currentId);
        if (byId!=null){
            return R.success(byId);
        }
        return R.error("查询失败");
    }
}
